﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

using AutoMapper;

using Revis.VClinicNet.Core.Domain;
using Revis.VClinicNet.Core.Domain.Repository;
using Revis.VClinicNet.App.Internal;
using Revis.VClinicNet.App.Internal.Dto;
using Revis.VClinicNet.App.Internal.Dto.Validation;

namespace Revis.VClinicNet.App.Internal.ServiceImpl
{
    public class EntryService : IEntryService
    {
        private IVisitRepository _visitRepository = null;
        private IDoctorRepository _doctorRepository = null;
        private IEntryRepository _entryRepository = null;

        public EntryService(IVisitRepository ivr, IDoctorRepository idr,
            IEntryRepository ier)
        {
            _visitRepository = ivr;
            _doctorRepository = idr;
            _entryRepository = ier;
        }

        public long Create(EntryCreateDto entryCreateDto)
        {
            Validation.For<EntryCreateDto>().Using<EntryCreateDtoRules>().Check(entryCreateDto);

            Visit visit = _visitRepository.Find(entryCreateDto.VisitId);
            if (visit == null) {
                throw new ClinicException("Nie znaleziono takiej wizyty");
            }
            Doctor doctor = _doctorRepository.Find(entryCreateDto.DoctorId);
            if (doctor == null) {
                throw new ClinicException("Nie znaleziono takiego lekarza");
            }

            EntryContent content = new EntryContent(
                entryCreateDto.Reason,
                entryCreateDto.Description,
                entryCreateDto.Recommendation);

            Entry entry = doctor.CheckUp(visit, content);

            _entryRepository.Store(entry);

            return entry.Id;
        }

        public TDto Find<TDto>(long entryId)
        {
            Entry entry = _entryRepository.Find(entryId);
            if (entry == null) {
                throw new ClinicException("Nie znaleziono takiego wpisu");
            }
            TDto dto = Mapper.Map<Entry, TDto>(entry);
            return dto;
        }


        public IList<EntryInfoDto> PatientCard(long patientId)
        {
            IList<Entry> entries = _entryRepository.PatientCard(patientId);
            if (entries == null) {
                entries = new List<Entry>();
            }
            IList<EntryInfoDto> infos = Mapper.Map<IList<Entry>, IList<EntryInfoDto>>(entries);
            return infos;
        }
    }
}
